import axios from 'axios';
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import baseurl from './baseurl';

const service = axios.create({
    baseURL: baseurl,
    timeout: 5000
});

service.interceptors.request.use(
    config => {
        if(localStorage.getItem('token') && config.url.indexOf('/login') === -1) {
            config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
        }
        return config;
    },
    error => {
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            if(response.config.responseType && response.config.responseType === 'blob'){//是否是下载请求
                return response;
            }else if(response.data.code === 90){//token失效
                localStorage.clear();
                location.href = process.env.VUE_APP_PUBLIC_PATH
                return Promise.reject();
            }else if(response.data.code === 0){//正常返回
                return response.data;
            }else{//其他错误
                Message({
                    message: response.data.message,
                    type: 'error'
                })
                return Promise.reject();
            }
        } else {
            return Promise.reject();
        }
    },
    error => {
        return Promise.reject();
    }
);

export default service;
